package com.dingyh.shopwebbackground.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingyh.shopwebbackground.entity.Advice;
import com.dingyh.shopwebbackground.entity.Evaluate;
import com.dingyh.shopwebbackground.entity.Orders;
import com.dingyh.shopwebbackground.entity.User;
import com.dingyh.shopwebbackground.service.EvaluateService;
import com.dingyh.shopwebbackground.service.OrdersService;
import com.dingyh.shopwebbackground.service.UserService;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-20
 */
@RestController
@CrossOrigin
@RequestMapping("/evaluate")
public class EvaluateController {

    @Autowired
    EvaluateService evaluateService;

    @Autowired
    UserService userService;

    @Autowired
    OrdersService ordersService;

    @RequestMapping("/allEvaluate")
    public CommonResult<Object> allEvaluate(String goodsId,@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.offsetPage((pageIndex - 1)*pageSize,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("goodsId",goodsId);
        List<Evaluate> evaluateList = evaluateService.allEvaluate(map);
        //用户id集合
        List<String> userIdList = evaluateList.stream().map(Evaluate::getUserid).collect(Collectors.toList());
        //key:用户id，value:昵称
        Map<String, String> nickNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userIdList)) {
            //查询用户昵称集合
            List<User> userList = userService.list(new LambdaQueryWrapper<User>()
                    .select(User::getId, User::getNickname)
                    .in(User::getId, userIdList));
            //转换为map格式
            nickNameMap.putAll(userList.stream().collect(Collectors.toMap(User::getId, User::getNickname)));
        }

        evaluateList.forEach(evaluate -> {
            evaluate.setUsername(nickNameMap.get(evaluate.getUserid()));
            User user = userService.getById(evaluate.getUserid());
            evaluate.setAvatar(user.getAvatar());
        });
        PageInfo<Evaluate> pageInfo = new PageInfo<>(evaluateList);
        return new CommonResult(200,"",pageInfo);
    }

    @RequestMapping("/allEvaluateByCompany")
    public CommonResult<Object> allEvaluateByCompany(String companyid,@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.offsetPage((pageIndex - 1)*pageSize,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("companyid",companyid);
        List<Evaluate> evaluateList = evaluateService.allEvaluateByCompany(map);
        //用户id集合
        List<String> userIdList = evaluateList.stream().map(Evaluate::getUserid).collect(Collectors.toList());
        //key:用户id，value:昵称
        Map<String, String> nickNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userIdList)) {
            //查询用户昵称集合
            List<User> userList = userService.list(new LambdaQueryWrapper<User>()
                    .select(User::getId, User::getNickname)
                    .in(User::getId, userIdList));
            //转换为map格式
            nickNameMap.putAll(userList.stream().collect(Collectors.toMap(User::getId, User::getNickname)));
        }

        evaluateList.forEach(evaluate -> {
            evaluate.setUsername(nickNameMap.get(evaluate.getUserid()));
            User user = userService.getById(evaluate.getUserid());
            evaluate.setAvatar(user.getAvatar());
        });
        PageInfo<Evaluate> pageInfo = new PageInfo<>(evaluateList);
        return new CommonResult(200,"",pageInfo);
    }

    /**
     * 新增评价
     * @param evaluate
     * @return
     */
    @RequestMapping("/addNewContent")
    public CommonResult<Object> addNewContent(Evaluate evaluate){
        Evaluate evaluateCurr = Evaluate.builder()
                .id(UUIDUtil.generator())
                .orderid(evaluate.getOrderid())
                .companyid(evaluate.getCompanyid())
                .userid(evaluate.getUserid())
                .star(evaluate.getStar())
                .goodsId(evaluate.getGoodsId())
                .usercontent(evaluate.getUsercontent())
                .timeadd(System.currentTimeMillis())
                .ifreply("0")
                .build();
        boolean result = evaluateService.save(evaluateCurr);
        Orders orders = ordersService.getById(evaluate.getOrderid());
        orders.setState("5");
        orders.setId(evaluate.getOrderid());
        User manageUser = userService.getById("3");
        manageUser.setMoney(manageUser.getMoney().subtract(orders.getAmount().multiply(BigDecimal.valueOf(0.8))));
        User user = userService.getById(orders.getCompanyid());
        user.setMoney(user.getMoney().add(orders.getAmount().multiply(BigDecimal.valueOf(0.8))));
        if (result && ordersService.updState(orders) && userService.updateById(manageUser) && userService.updateById(user) ) {
            return new CommonResult(200, "提交成功！", null);
        } else {
            return new CommonResult(500, "提交失败！", null);
        }
    }

    @RequestMapping("/addSaleContent")
    public CommonResult<Object> addSaleContent(Evaluate evaluate){
        evaluate.setTimereply(System.currentTimeMillis());
        if(evaluateService.addSaleContent(evaluate)){
            return new CommonResult(200, "修改成功！", null);
        }else {
            return new CommonResult(500, "修改失败！", null);
        }
    }

    @RequestMapping("/removeEvaluate")
    public CommonResult<Object> removeEvaluate(String id){
        if (evaluateService.removeEvaluate(id)){
            return new CommonResult(200, "删除成功！", null);
        }else{
            return new CommonResult(500, "删除失败！", null);
        }
    }

    @RequestMapping("selectByOrderId")
    public CommonResult<Object> selectByOrderId(String orderid) {
       Evaluate evaluate = evaluateService.selectByOrderId(orderid);
       return new CommonResult(200,"",evaluate);
    }

}

